'use strict';
// cloudfunctions/statistics/index.js
const db = uniCloud.database()
const uniID = require('uni-id-common')
const $ = db.command.aggregate  // 添加这行引入聚合操作符

exports.main = async (event, context) => {
  const { action, params } = event
  const uniIDIns = uniID.createInstance({ // 创建uni-id实例
      context: context,
      // config: {} // 完整uni-id配置信息，使用config.json进行配置时无需传此参数
    })
    const payload = await uniIDIns.checkToken(event.uniIdToken) // 后续使用uniIDIns调用相关接口
    const userId=payload.uid
	params['userId']=userId
  switch (action) {
    case 'getDealStatistics':
      return await getDealStatistics(params)
    case 'getDealList':
      return await getDealList(params)
    case 'exportDealData':
      return await exportDealData(params)
	case 'getChartData':
		return await getChartData(params)
    default:
      return { code: 400, message: '未知操作' }
  }
}

// 获取统计数据
async function getDealStatistics(params) {
  const { startDate, endDate, dimension, userId, deptId, multiDepts } = params
  
  // 构建查询条件
  let query = db.collection('mydb-customer')
    .where({
      status: '成交', // 只统计成交状态的客户
      update_date: db.command.gte(new Date(startDate)).and(db.command.lte(new Date(endDate)))
    })
  
  // 根据维度添加条件
  if (dimension === 'personal' && userId) {
    query = query.where({ creator_id: userId })
  } else if (dimension === 'department' && deptId) {
    // 这里需要根据实际业务逻辑查询部门关联的客户
    // 假设通过关联用户表查询
    const userQuery = await db.collection('uni-id-users').where({ department: deptId }).get()
    const userIds = userQuery.result.data.map(user => user._id)
    query = query.where({ creator_id: db.command.in(userIds) })
  } else if (dimension === 'multi-department' && multiDepts.length > 0) {
    const userQueries = await Promise.all(
      multiDepts.map(deptId => 
        db.collection('uni-id-users').where({ department: deptId }).get()
      )
    )
    const userIds = userQueries.flatMap(query => query.result.data.map(user => user._id))
    query = query.where({ creator_id: db.command.in(userIds) })
  }
  
  // 获取成交客户列表
  const dealCustomers = await query.get()
  console.log('dealCustomers',dealCustomers)
  // 计算统计数据
  const statistics = {
    totalDeals: dealCustomers.data.length,
    totalAmount: 0,
    totalServiceFee: 0,
    avgAmount: 0
  }
  
  // 获取客户详细信息计算金额
  for (const customer of dealCustomers.data) {
    const customerDetail = await db.collection('mydb-customer-fields')
      .where({ customerId: customer._id })
      .get()
    
    if (customerDetail.result.data.length > 0) {
      const detail = customerDetail.result.data[0]
      const amount = parseFloat(detail.requiredAmount) || 0
      // 假设服务费是成交金额的5%，可根据业务调整
      const serviceFee = amount * 0.05
      
      statistics.totalAmount += amount
      statistics.totalServiceFee += serviceFee
    }
  }
  
  statistics.avgAmount = statistics.totalDeals > 0 ? 
    (statistics.totalAmount / statistics.totalDeals).toFixed(2) : 0
  
  return { code: 200, data: statistics }
}
// 在 statistics 云函数中添加 getChartData 方法

// 获取图表数据
async function getChartData(params) {
  const { startDate, endDate, dimension, userId, deptId, multiDepts, chartType, timeType } = params
  
  switch (chartType) {
    case 'trend':
      return await getTrendChartData(params)
    case 'product':
      return await getProductChartData(params)
    case 'department':
      return await getDepartmentChartData(params)
    default:
      return await getTrendChartData(params)
  }
}

// 获取趋势图表数据
async function getTrendChartData(params) {
  const { startDate, endDate, timeType } = params
  
  // 构建时间分组
  const groupFormat = getTimeGroupFormat(timeType)
  
  const aggregation = db.collection('mydb-customer')
    .aggregate()
    .match({
      status: '成交',
      update_date: db.command.gte(new Date(startDate)).and(db.command.lte(new Date(endDate)))
    })
    .group({
      _id: {
        date: {
          $dateToString: {
            format: groupFormat,
            date: '$update_date'
          }
        }
      },
      dealCount: $.sum(1),
      totalAmount: $.sum(0), // 先初始化为0，后面再计算
      totalServiceFee: $.sum(0)
    })
    .sort({
      '_id.date': 1
    })
  
  const trendData = await aggregation.end()
  console.log('trendData',trendData)
  // 计算每个时间段的金额数据
  for (let item of trendData.data) {
    const date = item._id.date
    const deals = await db.collection('mydb-customer')
      .aggregate()
      .match({
        status: '成交',
        update_date: {
          $gte: new Date(startDate),
          $lte: new Date(endDate)
        }
      })
      .lookup({
        from: 'mydb-customer-fields',
        localField: '_id',
        foreignField: 'customerId',
        as: 'details'
      })
      .match({
        $expr: {
          $eq: [
            {
              $dateToString: {
                format: groupFormat,
                date: '$update_date'
              }
            },
            date
          ]
        }
      })
      .end()
    
    let totalAmount = 0
    let totalServiceFee = 0
    
    deals.forEach(deal => {
      if (deal.details && deal.details.length > 0) {
        const amount = parseFloat(deal.details[0].requiredAmount) || 0
        totalAmount += amount
        totalServiceFee += amount * 0.05 // 5%服务费
      }
    })
    
    item.totalAmount = totalAmount
    item.totalServiceFee = totalServiceFee
    item.date = date
  }
  
  return { code: 200, data: trendData }
}

// 获取产品分布数据
async function getProductChartData(params) {
  const aggregation = db.collection('mydb-customer')
    .aggregate()
    .match({
      status: '成交',
      update_date: db.command.gte(new Date(params.startDate)).and(db.command.lte(new Date(params.endDate)))
    })
    .lookup({
      from: 'mydb-customer-fields',
      localField: '_id',
      foreignField: 'customerId',
      as: 'details'
    })
    .group({
      _id: '$details.intendedProduct',
      count: $.sum(1)
    })
    .sort({
      count: -1
    })
    .limit(10) // 只显示前10个产品
  
  const productData = await aggregation.end()
  
  const result = productData.map(item => ({
    product: item._id[0] || '未分类',
    count: item.count
  }))
  
  return { code: 200, data: result }
}

// 获取部门分布数据
async function getDepartmentChartData(params) {
  const aggregation = db.collection('mydb-customer')
    .aggregate()
    .match({
      status: '成交',
      update_date: db.command.gte(new Date(params.startDate)).and(db.command.lte(new Date(params.endDate)))
    })
    .lookup({
      from: 'uni-id-users',
      localField: 'creator_id',
      foreignField: '_id',
      as: 'creator'
    })
    .lookup({
      from: 'mydb-customer-fields',
      localField: '_id',
      foreignField: 'customerId',
      as: 'details'
    })
    .group({
      _id: '$creator.department',
      totalAmount: $.sum({
        $cond: {
          if: { $gt: [{ $arrayElemAt: ['$details.requiredAmount', 0] }, 0] },
          then: { $toDouble: { $arrayElemAt: ['$details.requiredAmount', 0] } },
          else: 0
        }
      })
    })
    .sort({
      totalAmount: -1
    })
    .limit(10) // 只显示前10个部门
  
  const deptData = await aggregation.end()
  const result = deptData.data.map(item => ({
    department: item._id[0] || '未分配部门',
    amount: item.totalAmount
  }))
  
  return { code: 200, data: result }
}

// 获取时间分组格式
function getTimeGroupFormat(timeType) {
  switch (timeType) {
    case 'day':
      return '%Y-%m-%d'
    case 'week':
      return '%Y-%U' // 年-周数
    case 'month':
      return '%Y-%m'
    case 'year':
      return '%Y'
    default:
      return '%Y-%m-%d'
  }
}
// 获取成交列表
async function getDealList(params) {
  const { startDate, endDate, dimension, userId, deptId, multiDepts, page = 1, pageSize = 10 } = params
  
  let query = db.collection('mydb-customer')
    .where({
      status: '成交',
      update_date: db.command.gte(new Date(startDate)).and(db.command.lte(new Date(endDate)))
    })
  
  // 维度筛选逻辑同上...
  
  // 分页查询
  const result = await query
    .skip((page - 1) * pageSize)
    .limit(pageSize)
    .get()
  console.log('result',result)
  // 构建表格数据
  const tableData = await Promise.all(
    result.data.map(async (customer) => {
      const detail = await db.collection('mydb-customer-fields')
        .where({ customerId: customer._id })
        .get()
      
      const customerDetail = detail.result.data[0] || {}
      const creator = await db.collection('uni-id-users').doc(customer.creator_id).get()
      
      return {
        id: customer._id,
        dealTime: customer.update_date,
        customerName: customer.name,
        dealDepartment: creator.result.data?.department || '',
        dealPerson: creator.result.data?.name || '',
        product: customerDetail.intendedProduct || '',
        dealType: customer.type || '',
        amount: customerDetail.requiredAmount || '0',
        serviceFee: (parseFloat(customerDetail.requiredAmount || 0) * 0.05).toFixed(2)
      }
    })
  )
  
  const total = await query.count()
  console.log('total',total)
  return {
    code: 200,
    data: {
      data: tableData,
      total: total.total
    }
  }
}

// 导出数据
async function exportDealData(params) {
  // 实现Excel导出逻辑
  // 这里可以调用uniCloud的导出服务或生成CSV文件
  return { code: 200, fileUrl: 'exported-file-url' }
}